import { _decorator, Component, input, Node, Input, EventKeyboard, KeyCode, Vec3, Size, view } from 'cc';
import { globalObserver } from '../Observer/GlobalObserver';
const { ccclass, property } = _decorator;

@ccclass('playerController')
export class playerController extends Component {

    private startPos: Vec3 = new Vec3();
    private currentPos: Vec3 = new Vec3();
    private pos: Vec3 = new Vec3();
    private area: Size = new Size();
    

    private keys: Map<number, boolean> = new Map();

    protected onLoad(): void {
        input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        input.on(Input.EventType.KEY_UP, this.onKeyUp, this);
    }

    onKeyDown(event: EventKeyboard){
        this.keys.set(event.keyCode, true);
    }

    onKeyUp(event: EventKeyboard){
        this.keys.set(event.keyCode, false);
    }

    /**
     * move(event: EventKeyboard){
        console.log(this.node.getPosition());
        switch (event.keyCode){
            case KeyCode.KEY_W:
                this.pos.y += 10;
                break;
            case KeyCode.KEY_A:
                this.pos.x -= 10;
                break;
            case KeyCode.KEY_S:
                this.pos.y -= 10;
                break;
            case KeyCode.KEY_D:
                this.pos.x += 10;
                break;
        }
        this.node.setPosition(this.pos);
    } 
     */
    

    start() {
        this.node.position = new Vec3(1000, 1000, 0);
        this.startPos = this.node.getPosition();
        this.pos = this.node.getPosition();
        this.area = view.getVisibleSize();
    }


    update(deltaTime: number) {
        this.currentPos.set(this.node.position);
        if (!this.currentPos.equals(this.startPos)){
                globalObserver.emit('update-position', this.node.position);
                this.startPos.set(this.currentPos);
        }

        let moved = false;

        if (this.keys.get(KeyCode.KEY_W) || this.keys.get(KeyCode.ARROW_UP)) {
            this.pos.y += 500 * deltaTime;
            moved = true;
        }
        if (this.keys.get(KeyCode.KEY_A) || this.keys.get(KeyCode.ARROW_LEFT)) {
            this.pos.x -= 500 * deltaTime;
            moved = true;
        }
        if (this.keys.get(KeyCode.KEY_S) || this.keys.get(KeyCode.ARROW_DOWN)) {
            this.pos.y -= 500 * deltaTime;
            moved = true;
        }
        if (this.keys.get(KeyCode.KEY_D) || this.keys.get(KeyCode.ARROW_RIGHT)) {
            this.pos.x += 500 * deltaTime;
            moved = true;
        }

        if (moved) {
            this.node.setPosition(this.pos);
        }
    }
}


